<?php
	/** 
	 * ThumbnailManager
	 * @author David Ivins
	 */
	class ThumbnailManager
	{
		private $_sdb;
		private $_s3;
		private $_config;
		private $_logger;

		/**
		 * __construct 
		 */
		public function __construct()
		{
			$this->_sdb = Zend_Registry::get('sdb'); 
			$this->_s3 = Zend_Registry::get('s3'); 
			$this->_config = Zend_Registry::get('config');
			$this->_logger = Zend_Registry::get('logger'); 
		}
		
		/**
		 * getThumbnail
		 */
		public function getThumbnail($media_id, $width)
		{
			# query thumbnail database for requested thumbnail of size widthXheight
			$query = "['media_id' = '$media_id'] intersection ['width' = '$width']";
			$response = $this->_sdb->query($this->_config->domain->name->thumbs, $query);
			

			if ($response->isSetQueryResult())
			{
				$items = $response->getQueryResult()->getItemName();

				# get the url of the thumbnail if is already exists
				# otherwise create a new thumbnail of the desired width
				if (isset($items[0]))
					$url = $this->getUrlOfThumbnail($items[0]);
				else
					$url = $this->createAndStoreThumbnail($media_id, $width, $height);
			}
			else
				$url = $this->createAndStoreThumbnail($media_id, $width, $height);

			return $url;
		}
		
		/**
		 * createAndStoreThumbnail
		 */
		private function createAndStoreThumbnail($media_id, $width)
		{
			# gather information about desired media
			$media = new Media();
			$media->load($media_id);

			# get media url and headers
			$media_s3_url = $media->getUrl();
			$media_headers = get_headers($media_s3_url, 1);

			# gather prerequisite thumbnail information
			$thumb_info = array();
			$thumb_info['headers']['Content-Type'] = $media_headers['Content-Type'];
			$thumb_info['access'] = S3::ACL_PUBLIC_READ;

			# get the binary of the thumbnail using the thumb_gen tool
			$thumb_binary = shell_exec($this->_config->path->scripts->dir . '/thumb_gen.php ' 
				. escapeshellarg($media_s3_url) . " " . escapeshellarg($width));
			
			# set up attributes for record
			$thumb_attributes = array(
				'media_id' => $media_id, 
				'width' => $width
			);

			# create and save thumbnail
			$thumbnail = new Thumbnail();
			$thumbnail->setBinaryInfo($thumb_binary, $thumb_info);
			$thumbnail->setAttributes($thumb_attributes);
			$thumbnail->save();

			# return the url of the newly created thumbnail
			return $thumbnail->getUrl();
		}
		
		/**
		 * getUrlOfThumbnail
		 */
		private function getUrlOfThumbnail($item)
		{
			$thumbnail = new Thumbnail();
			$thumbnail->load($item);
			return $thumbnail->getUrl();
		}
	}
